package com.fruit.controller.app.user;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.druid.util.StringUtils;
import com.fruit.controller.base.BaseController;
import com.fruit.pojo.common.Page;
import com.fruit.pojo.order.OrderGood;
import com.fruit.pojo.user.Follow;
import com.fruit.pojo.user.Region;
import com.fruit.pojo.user.Address;
import com.fruit.pojo.user.ComAccount;
import com.fruit.pojo.user.UserInfo;
import com.fruit.service.pic.PictureManager;
import com.fruit.service.user.UserManager;
import com.fruit.util.CookieUtil;
import com.fruit.util.CustomUtil;
import com.fruit.util.MessagesCode;
import com.fruit.util.ResultInfo;

@Controller
@RequestMapping(value = "/app/user/")
public class UserController extends BaseController {

	@Autowired
	private UserManager userService;

	@Autowired
	private PictureManager PictureService;

	// 用户信息
	@RequestMapping(value = "userCenter", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> userCenter(HttpSession session, HttpServletRequest request) {
		this.logBefore(logger, "用户信息");
		Map<String, Object> resMap = new HashMap<String, Object>();
		String id = request.getParameter("userId");
		if (StringUtils.isEmpty(id)) {
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
			return resMap;
		}
		try {
			UserInfo user = userService.getUser(Integer.parseInt(id));
			if (user != null) {
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "查询成功!"));
				resMap.put("user", user);
			} else {
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_ISnULL, "未找到用户!"));
			}
		} catch (Exception e) {
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		return resMap;
	}

	// 收货地址信息
	@RequestMapping(value = "addressList", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> addressList(String userId, HttpSession session, HttpServletRequest request) {
		this.logBefore(logger, "收货地址信息");
		Map<String, Object> resMap = new HashMap<String, Object>();
		Map<String, Object> parame = new HashMap<String, Object>();
		if (StringUtils.isEmpty(userId)) {
			resMap.put("result", this.initResult(ResultInfo.ERROR, "parame-error", "参数错误!"));
			return resMap;
		}
		parame.put("userId", userId);
		try {
			List<Address> address = userService.getAddressList(parame);
			if (address.size() > 0) {
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "查询成功!"));
				resMap.put("address", address);
			} else {
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_ISnULL, "还未设置收货地址!"));
			}
		} catch (Exception e) {
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		return resMap;
	}

	// 添加收货地址
	@RequestMapping(value = "saveAddress", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> saveAddress(Address address, HttpSession session, HttpServletRequest request) {
		this.logBefore(logger, "添加收货地址");
		Map<String, Object> resMap = new HashMap<String, Object>();
		Map<String, Object> parame = new HashMap<String, Object>();
		try {
			if (address == null) {
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
			} else {
				parame.put("userId", address.getUserId());
				List<Address> addres = userService.getAddressList(parame);
				if (addres != null) {
					for (Address addre : addres) {
						if("01".equals(address.getStatus())){
							if ("01".equals(addre.getStatus())) {
								addre.setStatus("00");
								userService.updateAddStatus(addre);
							}
						}
					}
				}
				userService.saveAddress(address);
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "添加成功!"));
			}
		} catch (Exception e) {
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		return resMap;
	}

	// 修改收货地址信息
	@RequestMapping(value = "addressMsg", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> addressMsg(int id, HttpSession session, HttpServletRequest request) {
		this.logBefore(logger, "收货地址信息");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			Address address = userService.getAddress(id);
			if (address != null) {
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "查询成功!"));
				resMap.put("address", address);
			} else {
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_ISnULL, "未找到收货地址!"));
			}
		} catch (Exception e) {
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		return resMap;
	}

	// 修改默认地址状态
	@RequestMapping(value = "updateStatus", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> updateStatus(int id, int userId, HttpSession session, HttpServletRequest request) {
		this.logBefore(logger, "修改默认地址状态");
		Map<String, Object> resMap = new HashMap<String, Object>();
		Map<String, Object> parame = new HashMap<String, Object>();
		if (id <= 0 || userId <= 0) {
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
			return resMap;
		}
		try {
			parame.put("userId", userId);
			List<Address> addres = userService.getAddressList(parame);
			if (addres != null) {
				for (Address addre : addres) {
					if ("01".equals(addre.getStatus())) {
						addre.setStatus("00");
						userService.updateAddStatus(addre);
					}
				}
			}
			Address add = new Address();
			add.setStatus("01");
			add.setId(id);
			userService.updateAddStatus(add);
			List<Address> addr = userService.getAddressList(parame);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "修改成功!"));
			resMap.put("address", addr);
		} catch (Exception e) {
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		return resMap;
	}

	// 修改收货地址
	@RequestMapping(value = "updateAddress", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> updateAddress(Address address, HttpSession session, HttpServletRequest request) {
		this.logBefore(logger, "修改收货地址");
		Map<String, Object> resMap = new HashMap<String, Object>();
		Map<String, Object> parame = new HashMap<String, Object>();
		try {
			if (address == null) {
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
			} else {
				if ("01".equals(address.getStatus())) {
					parame.put("userId", address.getUserId());
					List<Address> addres = userService.getAddressList(parame);
					if (addres != null) {
						for (Address addre : addres) {
							if ("01".equals(addre.getStatus())) {
								addre.setStatus("00");
								userService.updateAddStatus(addre);
							}
						}
					}
				}
				userService.updateAddress(address);
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "修改成功!"));
			}
		} catch (Exception e) {
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		return resMap;
	}

	// 删除收货地址
	@RequestMapping(value = "deleteAddress", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> deleteAddress(Address address, HttpSession session, HttpServletRequest request) {
		this.logBefore(logger, "删除收货地址");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			if (address == null) {
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
			} else {
				userService.deleteAddress(address.getId());
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "删除成功!"));
			}
		} catch (Exception e) {
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		return resMap;
	}

	/**
	 * 地区下拉信息
	 */
	@RequestMapping(value = "regionList", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> regionList(int id) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (id < 0) {
				map.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数错误!"));
			} else {
				List<Region> list = userService.regionList(id);
				map.put("list", list);
				map.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "查询成功!"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	// app用户信息修改 昵称 ,性别
	@RequestMapping(value = "userAlter", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> appUpdateUser(UserInfo user, HttpSession session, HttpServletRequest request) {
		this.logBefore(logger, "用户修改");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			if (user == null) {
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
				return resMap;
			} else if (user.getSex() != null) {
				if (!"女".equals(user.getSex()) && !"男".equals(user.getSex())) {
					resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数错误!"));
					return resMap;
				}
			} 
			UserInfo us = userService.getUser(user.getId());
			if(us ==null){
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "用户不存在!"));
				return resMap;
			}
			user.setVersion(us.getVersion());
			userService.updateUserMess(user);
			UserInfo use = userService.getUser(user.getId());
			if (use != null) {
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "修改成功"));
				resMap.put("user", use);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.SYSTEM, "网络繁忙!"));
		}
		return resMap;
	}

	// app头像修改
	@RequestMapping(value = "headImage", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> groupImage(HttpSession session, HttpServletResponse response,
			HttpServletRequest request) {
		this.logBefore(logger, "头像修改");
		Map<String, Object> resMap = new HashMap<String, Object>();
		String id = request.getParameter("userId");
		if (StringUtils.isEmpty(id)) {
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
			return resMap;
		}
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			System.out.println("ss");
		}
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("file");
		InputStream in = null;
		try {
			in = file.getInputStream();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			UserInfo user = userService.getUser(Integer.parseInt(id));
			String path = "/personal/" + user.getCodePre() + id + user.getCodeSuf();
			Map imagePath = PictureService.uploadPictureFile(in, path, "head.png");
			String imageAddress = (String) imagePath.get("url");
			user.setHeadImage(imageAddress+ "?v" + CustomUtil.buildRandom(4));
			userService.updateUserHeadImage(user);
			UserInfo use = userService.getUser(Integer.parseInt(id));
			if (use != null) {
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "修改成功!"));
				resMap.put("user", use);
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.SYSTEM, "系统繁忙!"));
		}
		return resMap;
	}

	/**
	 * 添加关注
	 */
	@RequestMapping(value = "saveFollow", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> saveFollow(HttpSession session, HttpServletResponse response,
			HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String userId = request.getParameter("userId");
		String goodsId = request.getParameter("goodsId");
		if (StringUtils.isEmpty(goodsId) || StringUtils.isEmpty(userId)) {
			map.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
			return map;
		}
		Follow follow = new Follow();
		follow.setGoodsId(Integer.parseInt(goodsId));
		follow.setUserId(Integer.parseInt(userId));
		try {
			int num = userService.getFollowNum(follow);
			if (num > 0) {
				map.put("result", this.initResult(ResultInfo.ERROR, "ERROR", "此商品已被关注!"));
				return map;
			}
			userService.saveFollow(follow);
			map.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "添加成功!"));
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", this.initResult(ResultInfo.ERROR, "ERROR", "网络繁忙!"));
		}
		return map;
	}

	/**
	 * 关注列表
	 */
	@RequestMapping(value = "followList", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> followList(Page page, String userId, HttpSession session, HttpServletResponse response,
			HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> parame = new HashMap<String, Object>();
		if (page.getPage() <= 0 || StringUtils.isEmpty(userId)) {
			map.put("result", this.initResult(ResultInfo.ERROR, "parame-error", "参数错误!"));
			return map;
		}
		parame.put("start", (page.getPage() - 1) * page.getShowNumber());
		parame.put("number", page.getShowNumber());
		parame.put("userId", userId);
		try {
			List<OrderGood> goods = userService.getFollowList(parame);
			if (goods.size() <= 0) {
				map.put("result", this.initResult(ResultInfo.ERROR, "ERROR", "还未关注商品!"));
			} else {
				map.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "查询成功!"));
				map.put("goods", goods);
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", this.initResult(ResultInfo.ERROR, "ERROR", "网络繁忙!"));
		}
		return map;
	}

	/**
	 * 删除关注
	 */
	@RequestMapping(value = "deleteFollow", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> deleteFollow(Follow follow, HttpServletResponse response, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (follow.getIds() == null || follow.getIds().length == 0 || follow.getUserId() <= 0) {
				map.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
			} else {
				userService.deleteFollow(follow);
				map.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "删除成功!"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", this.initResult(ResultInfo.ERROR, "ERROR", "网络繁忙!"));
		}
		return map;
	}

	/**
	 * 获取联系方式
	 */
	@RequestMapping(value = "getContact", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> getContact(HttpServletResponse response, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			ComAccount ca = userService.getContact();
			if (ca != null) {
				map.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "查询成功!"));
				map.put("msg", ca);
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", this.initResult(ResultInfo.ERROR, "ERROR", "网络繁忙!"));
		}
		return map;
	}
	
	@RequestMapping(value = "getUserToken", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> getUserToken(HttpServletRequest request,HttpServletResponse response, HttpSession session, int loginId){
		this.logBefore(logger, "获取UserToken");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		session.removeAttribute("loginId");
		session.setAttribute("loginId", loginId);
		resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "成功"));
		resMap.put("sessionId", session.getId());
		}catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.SYSTEM, "系统繁忙!"));
		}
		this.logAfter(logger);
		return resMap;
	}	
	
}
